<template>
  <view class="container">
 

    <scroll-view scroll-y class="scroll-content" 
                 refresher-enabled="true" 
                 :refresher-triggered="refreshing" 
                 @refresherrefresh="onRefresh">
      

      <view class="habit-list">

      <view class="section-title">今日习惯</view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <uni-load-more status="loading" :content-text="{ contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '加载中...' }"></uni-load-more>
      </view>

      <!-- 错误状态 -->
      <view v-else-if="error" class="error-container">
        <view class="error-message">{{ error }}</view>
        <button class="retry-button" @click="loadHabits">重试</button>
      </view>

      <!-- 空状态 -->
      <view v-else-if="habits.length === 0" class="empty-container">
        <view class="empty-icon">
          <text class="fa-solid fa-calendar-check" style="font-size: 48px; color: #CCCCCC;"></text>
        </view>
        <view class="empty-message">还没有习惯记录</view>
        <view class="empty-tip">点击右下角按钮创建第一个习惯吧</view>
      </view>

      <!-- 习惯列表 -->
      <view v-else class="habit-card" v-for="habit in habits" :key="habit.id">
        <view class="habit-item">
          <view class="habit-icon-wrapper" :style="{ backgroundColor: habit.bgColor }">
            <text :class="['fa-solid', habit.icon]" :style="{ fontSize: '24px', color: habit.iconColor }"></text>
          </view>
          <view class="habit-info">
            <text class="habit-name">{{ habit.name }}</text>
            <text class="habit-days" v-if="habit.days > 0">已坚持 <text class="highlight-days">{{ habit.days }}</text> 天</text>
            <text class="habit-progress" v-else-if="habit.progress">目标: {{ habit.progress.target }}{{ habit.progress.unit }}, 今日: {{ habit.progress.current }}/{{ habit.progress.target }}</text>
            <text class="habit-target" v-else-if="habit.targetValue && habit.unit">目标: {{ habit.targetValue }}{{ habit.unit }}</text>
          </view>
          <view class="habit-action" @click="toggleHabitCompletion(habit.id)">
            <uni-icons v-if="habit.completed" type="checkbox-filled" size="28" color="#4CAF50"></uni-icons>
            <uni-icons v-else type="circle" size="28" color="#CCCCCC"></uni-icons>
          </view>
        </view>
      </view>


      <!-- 图片区域 -->
      <view class="image-card">
        <image src="/static/images/water-bottle.jpg" 
        mode="aspectFill" 
        class="water-image"></image>
      </view>
    </view>
    </scroll-view>



    <!-- 浮动操作按钮 -->
    <uni-fab
      ref="fab"
      :pattern="pattern"
      :content="content"
      :horizontal="'right'"
      :vertical="'bottom'"
      :direction="'horizontal'"
      @trigger="trigger"
      @fabClick="fabClick"
    ></uni-fab>

  </view>
</template>

<script>
import { habitsApi } from '@/api/index'

export default {
  data() {
    return {
      habits: [],
      loading: false,
      refreshing: false,
      error: null,
      pattern: {
        color: '#FFFFFF',
        backgroundColor: '#4CAF50',
        selectedColor: '#4CAF50',
        buttonColor: '#4CAF50',
        iconColor: '#FFFFFF'
      },
      content: [
        // { iconPath: '/static/icon-habit.png', selectedIconPath: '/static/icon-habit-active.png', text: '习惯', active: false },
        // { iconPath: '/static/icon-todo.png', selectedIconPath: '/static/icon-todo-active.png', text: '待办', active: false }
      ]
    };
  },
  onLoad() {
    uni.$on('navigationBarButtonTap', (e) => {
      console.log(`Hello`)
    })
    console.log('Habits page loaded');
    this.loadHabits();
  },
  // 处理导航栏按钮点击事件
  onNavigationBarButtonTap(e) {
    if (e.index === 0) { // 设置按钮
      this.goToSettings();
    }
  },
  methods: {
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true;
      await this.loadHabits(true);
      this.refreshing = false;
    },
    
    // 加载习惯列表
    async loadHabits(isRefresh = false) {
      try {
        if (!isRefresh) {
          this.loading = true;
        }
        this.error = null;
        
        const response = await habitsApi.getHabitsList();
        
        // 处理API返回的数据，添加UI所需的字段
        this.habits = response.data.data.list.map(habit => ({
          ...habit,
          // 为每个习惯添加默认的UI样式
          bgColor: habit.bgColor || this.getDefaultBgColor(habit.category),
          icon: habit.icon || this.getDefaultIcon(habit.category),
          iconColor: habit.iconColor || this.getDefaultIconColor(habit.category),
          // 映射后端数据字段到UI显示字段
          days: habit.streak, // 使用 streak 作为连续天数
          progress: habit.targetValue > 1 ? {
            target: habit.targetValue,
            current: 0, // 今日进度需要从完成记录中获取
            unit: habit.unit
          } : null,
          // 今日完成状态需要通过查询今日记录来确定
          completed: false // 默认未完成，需要单独查询今日状态
        }));
        
        // 获取今日完成状态
        await this.loadTodayCompletionStatus();
        
      } catch (error) {
        console.error('加载习惯列表失败:', error.stack);
        this.error = '加载习惯列表失败，请重试';
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载今日完成状态
    async loadTodayCompletionStatus() {
      const today = new Date().toISOString().split('T')[0];
      
      for (const habit of this.habits) {
        try {
          // 获取习惯的历史记录，查找今日记录
          const response = await habitsApi.getHabitHistory(habit.id, {
            startDate: today,
            endDate: today,
            page: 1,
            pageSize: 1
          });
          
          const todayRecord = response.data.data.list.find(record => record.date === today);
          if (todayRecord) {
            habit.completed = todayRecord.completed;
            // 如果有进度显示，更新当前进度
            if (habit.progress && todayRecord.completed) {
              habit.progress.current = todayRecord.value || 0;
            }
          }
        } catch (error) {
          console.warn(`获取习惯 ${habit.name} 今日状态失败:`, error);
          // 忽略单个习惯的错误，继续处理其他习惯
        }
      }
    },
    
    // 切换习惯完成状态
    async toggleHabitCompletion(id) {
      const habit = this.habits.find(h => h.id === id);
      if (!habit) return;
      
      const originalCompleted = habit.completed;
      
      try {
        // 先更新UI状态
        habit.completed = !habit.completed;
        
        // 调用API更新后端状态
        if (habit.completed) {
          await habitsApi.markHabitComplete(id, {
            date: new Date().toISOString().split('T')[0], // 格式化为 YYYY-MM-DD
            value: habit.targetValue,
            note: ''
          });
        } else {
          await habitsApi.unmarkHabitComplete(id, {
            date: new Date().toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
          });
        }
        
        uni.showToast({
          title: habit.completed ? '习惯已完成' : '习惯未完成',
          icon: 'success'
        });
        
        // 重新加载数据以获取最新状态
        this.loadHabits();
        
      } catch (error) {
        // 如果API调用失败，恢复原始状态
        habit.completed = originalCompleted;
        console.error('更新习惯状态失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'error'
        });
      }
    },
    
    // 获取默认背景色
    getDefaultBgColor(category) {
      const colorMap = {
        health: '#E6FFF2',
        study: '#EBF2FF',
        exercise: '#FFF0E6',
        lifestyle: '#FFF8E1',
        work: '#F3E5F5'
      };
      return colorMap[category] || '#F5F5F5';
    },
    
    // 获取默认图标
    getDefaultIcon(category) {
      const iconMap = {
        health: 'fa-heart',
        study: 'fa-book',
        exercise: 'fa-running',
        lifestyle: 'fa-coffee',
        work: 'fa-briefcase'
      };
      return iconMap[category] || 'fa-star';
    },
    
    // 获取默认图标颜色
    getDefaultIconColor(category) {
      const colorMap = {
        health: '#00CC66',
        study: '#4080FF',
        exercise: '#FF6B35',
        lifestyle: '#F7B500',
        work: '#9C27B0'
      };
      return colorMap[category] || '#666666';
    },
    trigger(e) {
      console.log(e);
      // uni.showToast({
      //   title: '点击了' + e.item.text,
      //   icon: 'none'
      // });
    },
    fabClick() {
      console.log('FAB clicked');
      // 在这里处理点击浮动操作按钮的逻辑，例如跳转到新增习惯页面
      uni.navigateTo({
        url: '/pages/habits/create'
      });
    },
    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/index'
      });
    },
    handleSearch() {
      uni.showToast({
        title: '搜索功能开发中',
        icon: 'none'
      });
    }
  }
};
</script>

<style lang="scss">
/* Font Awesome已在App.vue中全局引入 */
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.nav-left {
  display: flex;
  align-items: center;
  padding-left: 15px;
}

.greeting {
  font-size: 20px;
  font-weight: bold;
  color: #333333;
}

.nav-right {
  display: flex;
  align-items: center;
  padding-right: 15px;
}

.settings-icon {
  margin-left: 15px;
}

.scroll-content {
  flex: 1;
  overflow-y: auto;
  padding-top: 88px;
}

.header-right {
  display: flex;
  align-items: center;
  padding-right: 15px;
}

.settings-icon {
  margin-left: 15px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-top: 10px;
  margin-bottom: 15px;
  padding-left: 5px;
}

.habit-list {
  padding: 0 16px 100px 16px;
}

.habit-card {
  padding: 10px 15px;
  background-color: #ffffff;
  border-radius: 10px;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}



.habit-item {
  display: flex;
  align-items: center;
}

.habit-icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  z-index: 1; /* 增加 z-index 确保图标显示在最上层 */
}

.habit-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.habit-name {
  font-size: 16px;
  color: #333333;
  font-weight: 500;
}

.habit-days,
.habit-progress,
.habit-target {
  font-size: 13px;
  color: #999999;
  margin-top: 2px;
}

.highlight-days {
  color: #4CAF50;
  font-weight: bold;
}

.habit-action {
  margin-left: 15px;
}

.image-card {
  background-color: #ffffff;
  border-radius: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.water-image {
  width: 100%;
  height: 128px;
  border-radius: 12px;
  opacity: 0.75;
}

.content-image {
  width: 100%;
  height: 128px;
  border-radius: 12px;
  opacity: 0.75;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 60px;
  background-color: #ffffff;
  border-top: 1px solid #f0f0f0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.tab-bar-text {
  font-size: 12px;
  color: #666666;
  margin-top: 2px;
}

.tab-bar-text.active {
  color: #4CAF50;
}

.fab-box {
  position: fixed;
  right: 30px;
  bottom: 80px; /* 调整位置以避免与底部导航栏重叠 */
}

.fab-button {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background-color: #4CAF50;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.fab-icon {
  color: #ffffff;
  font-size: 28px;
}

/* 加载状态样式 */
.loading-container {
  padding: 40px 20px;
  text-align: center;
}

/* 错误状态样式 */
.error-container {
  padding: 40px 20px;
  text-align: center;
}

.error-message {
  font-size: 16px;
  color: #FF6B6B;
  margin-bottom: 20px;
}

.retry-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 10px 20px;
  font-size: 14px;
}

.retry-button:active {
  background-color: #45A049;
}

/* 空状态样式 */
.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-message {
  font-size: 18px;
  color: #666666;
  margin-bottom: 10px;
  font-weight: 500;
}

.empty-tip {
  font-size: 14px;
  color: #999999;
}
</style>